package com.woniu.controller.config.init;


import com.woniu.model.mallSystem.entity.China;
import com.woniu.model.mallSystem.gh.common.RedisConstant;
import com.woniu.service.mallSystem.IChinaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 省市区数据预热
 */
@Component
public class InitChinaAddressRunner implements CommandLineRunner {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IChinaService chinaService;
    @Override
    public void run(String... args) throws Exception {
        // 判断：缓存中没有数据才去查询
        if(!redisTemplate.hasKey(RedisConstant.CHINA_CACHE)){
            // 查询所有省市区
            List<China> list = chinaService.list();
            //遍历，加入到Redis的hash
            list.forEach(china -> {
                redisTemplate.opsForHash().put(RedisConstant.CHINA_CACHE,china.getId().toString(),china.getName());
            });
        }
    }
}
